<?php

declare(strict_types=1);

namespace app\admin\logic\server;
use app\common\model\server\Consumer;
use app\common\model\server\Chats;
use app\api\controller\Event;
use app\admin\logic\server\BanwordLogic;
use app\admin\logic\server\ConsumerLogic;
use app\common\model\system\SysUser;
/**
 * 聊天记录
 */
class ChatsLogic  
{

    /**
     * @notes 聊天记录列表
     * @param array $param
     * @return \think\response\Json
     */
    public static function lists(array $param)
    {
        
        if(isset($param['uid']) && $param['uid'] && isset($param['kefu_id']) && $param['kefu_id']){
            cache('kefu_first_id_'.$param['kefu_id'],$param['uid']);
        }  
        $list = Chats::custom($param)
            ->with(['user','kefu'])
            ->order('id desc')
            ->pages($param)
            ->select();
            
        
        return list_fmt($list, Chats::custom($param)->count(),'',$param);
    }
    /**
     * 获取用户聊天历史记录
     *
     * @param int $uid 用户ID
     * @return array
     */
    public static function getMsgList($uid){
        return self::getAll(['uid'=>$uid]);
    }
     /**
     * 撤销消息
     *
     * @param array $data 操作数据
     * @return void
     */
    public static function cancel($data){
        Chats::where('unstr', $data['unstr'])->delete();
        Event::sendUid($data['uid'], ['type'=>'cancel','msg'=>'成功','data'=>$data['unstr']]);
    }
    /**
     * 发送消息并处理后续逻辑
     *
     * @param array $data 消息数据，含内容、方向、用户ID、客服ID等
     * @return void
     */
    public static function sendMessage(array $data): void
    {
        // 过滤并清理消息内容中的敏感词与空白字符
        //登录后获取在线用户列表
        
        
        $data['state'] =1;
        $data['content'] = BanwordLogic::replaceMsg(trim($data['content']));
        if($data['uid'] == cache('kefu_first_id_'.$data['kefu_id'])){ //当前客户的uid  和缓存uid保持一致,则标记为已读
            $data['state'] =2;
        }
        // 保存消息记录
        $chat = Chats::create($data);
        // 获取接收方信息
        if($data['uid'] ){
            $userInfo = ConsumerLogic::detail(['uid' => $chat->uid]);
            //修改用户数据
            if($chat->state ==1 && $data['direction']==1){ //未读状态 增加客户的未读数量
                Consumer::where('uid',$chat->uid)->inc('read_num')->update();
                $userInfo['read_num']=(int) $userInfo['read_num']+1;
            }
        }
        // 准备发送的数据包，包含时间戳和用户信息
        $data['created_at']=time();
        $sendMessagePayload = [
            'user' => $userInfo,
            'msg' => '成功',
            'data' => $data,
        ];
         // 定义接收消息的用户ID
        $receiverId = $data['direction'] === 1 ? $data['kefu_id'] : $data['uid'];
        // 发送消息通知
        Event::sendUid($receiverId, array_merge(['type' => 'msg'], $sendMessagePayload));
        
        // 转接客服处理
        if ($data['direction'] === 3) {
            // 获取被转接客服信息
            $serverInfo = SysUser::where('id', $data['switch_id'])->field('id, nickname, avatar')->find();
            if ($serverInfo) {
                // 通知用户转接的客服信息
                Event::sendUid($data['uid'], [
                    'type' => 'serverdetail',
                    'msg' => '成功',
                    'data' => $serverInfo
                ]);
                // 更新转接客服的在线用户列表
                ConsumerLogic::sendOnlineList($data['switch_id']);
            }
        }
            
            
        if (empty($data['kefu_id'])) {
            // 未指定客服，加入排队列表
            ConsumerLogic::addPdList($data);
        }
    }
     /**
     * 删除单条聊天记录
     *
     * @param int $id 聊天记录ID
     * @return bool
     */
    public function delete($id)
    {
        return Chats::whereIn('id',$id)->delete();
    }
    public static function edit(array $param)
    {
        return !empty($param['id']) ? Chats::update($param) : Chats::create($param);
    }
    /**
     * 获取所有聊天记录
     *
     * @param array $where 查询条件
     * @return array
     */
    public static function getAll($where){
        $data= Chats::with('kefu')->where($where)->order('id asc')->select();
        return !empty($data) ? $data->toArray() : [];
    }
    //将所有未读信息 更新为已读信息
    public function read($param){
        $res = true;
        try{
            Chats::where($param)->update(['state'=>2]);
            Consumer::where($param)->update(['read_num'=>0]);
        } catch (Exception $e) {
            $res = false;
        }  
        return $res;
        
    }
}
